/**
 * 
 */
package com.apache.flow.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.ProcessInstanceQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.apache.common.FlowBaseAction;
import com.apache.core.utils.web.struts2.Struts2Utils;
import com.apache.flow.vo.ProcessInstanceVo;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;

@Namespace("/flow/core")
@Results({})
public class FlowInstanceAction extends FlowBaseAction {
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(FlowInstanceAction.class);
	/**
	 * 流程引擎
	 */
	@Autowired
	private ProcessEngine processEngine;

	/**
	 * 流程定义ID
	 */
	private String processDefinitionId;
	/**
	 * 流程实例id
	 */
	private String processInstanceId;

	private String rows;

	private String page;

	private String proInsIds;

	/**
	 * 删除流程实例
	 * @return String
	 * @throws IOException 
	 */
	public String del() throws IOException {
		try {
			logger.info("删除流程实例  processInstanceId=" + processInstanceId);
			ExecutionService executionService = processEngine.getExecutionService();
			//executionService.deleteProcessInstance(processInstanceId);
			//删除实例，包含历史数据
			executionService.deleteProcessInstanceCascade(processInstanceId);
			showOk("删除流程实例成功！");
		} catch (Exception e) {
			logger.debug("删除流程实例" + processInstanceId + "失败！" + e);
			showError("删除流程实例失败！");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除流程实例
	 * @return String
	 * @throws IOException 
	 */
	public String batchDel() throws IOException {
		try {
			logger.info("批量删除流程实例(包含历史数据)  proInsIds=" + proInsIds);
			ExecutionService executionService = processEngine.getExecutionService();
			if (StrUtil.isNull(proInsIds)) {
				showError("参数proInsIds为空！");
				return null;
			}

			String[] ids = proInsIds.split(",");
			for (int i = 0; i < ids.length; i++) {
				executionService.deleteProcessInstanceCascade(ids[i]);
			}
			showOk("批量删除流程实例成功！");
		} catch (Exception e) {
			logger.debug("批量删除流程实例" + proInsIds + "失败！" + e);
			showError("批量删除流程实例失败！");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 得到所有流程实例
	 * @return String
	 */
	public String data() {
		int pageNo = NumberUtils.getInt(page, 1);
		int pageSize = NumberUtils.getInt(rows, 15);
		int startIndex = (pageNo - 1) * pageSize;

		//管理流程实例
		ExecutionService executionService = processEngine.getExecutionService();
		ProcessInstanceQuery processInstanceQuery = executionService.createProcessInstanceQuery();
		int sumCount = 0;
		List<ProcessInstance> list = null;

		if (StrUtil.isNotNull(processInstanceId)) {//2015-12-125
			sumCount = processInstanceQuery.processInstanceId(processInstanceId).list().size();
			list = processInstanceQuery.processInstanceId(processInstanceId)
					.orderDesc(ProcessInstanceQuery.PROPERTY_KEY).page(startIndex, pageSize).list();
		} else if (StrUtil.isNotNull(processDefinitionId)) {
			sumCount = processInstanceQuery.processDefinitionId(processDefinitionId).list().size();
			list = processInstanceQuery.processDefinitionId(processDefinitionId)
					.orderDesc(ProcessInstanceQuery.PROPERTY_KEY).page(startIndex, pageSize).list();
		} else {
			sumCount = processInstanceQuery.list().size();
			list = processInstanceQuery.orderDesc(ProcessInstanceQuery.PROPERTY_KEY).page(startIndex, pageSize).list();
		}

		List<ProcessInstanceVo> piVolist = new ArrayList<ProcessInstanceVo>();
		for (ProcessInstance pi : list) {
			ProcessInstanceVo piVo = new ProcessInstanceVo();
			piVo.setId(pi.getId());
			piVo.setName(pi.getName());
			piVo.setKey(pi.getKey());
			piVo.setState(pi.getState());
			piVo.setDefinitionId(pi.getProcessDefinitionId());
			piVo.setIsSuspended(String.valueOf(pi.isSuspended()));
			piVo.setIsEnd(String.valueOf(pi.isEnded()));
			piVolist.add(piVo);
		}
		JSONObject json = new JSONObject();
		json.put("total", sumCount);
		json.put("rows", piVolist);
		try {
			Struts2Utils.getResponse().getWriter().write(json.toString());
		} catch (IOException e) {
			logger.debug("得到流程实例数据错误" + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据流程定义id得到流程实例
	 * @return String
	 */
	public String dataByDefinitionId() {
		//管理流程实例
		ExecutionService executionService = processEngine.getExecutionService();
		List<ProcessInstance> list = executionService.createProcessInstanceQuery()
				.processDefinitionId(processDefinitionId).list();
		JSONObject json = new JSONObject();
		json.put("total", 4);
		json.put("rows", list);
		try {
			Struts2Utils.getResponse().getWriter().write(json.toString());
		} catch (IOException e) {
			logger.debug("得到流程实例数据错误" + e);
			e.printStackTrace();
		}
		return null;
	}

	public String getProcessDefinitionId() {
		return processDefinitionId;
	}

	public void setProcessDefinitionId(String processDefinitionId) {
		this.processDefinitionId = processDefinitionId;
	}

	public String getProcessInstanceId() {
		return processInstanceId;
	}

	public void setProcessInstanceId(String processInstanceId) {
		this.processInstanceId = processInstanceId;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getProInsIds() {
		return proInsIds;
	}

	public void setProInsIds(String proInsIds) {
		this.proInsIds = proInsIds;
	}

}
